import axios from 'axios'
import store from '../store/index'
import { Error } from './error'

const service = axios.create({
  baseURL: '/api'
})

service.interceptors.request.use(
  config => {
    if (config.method.toLowerCase() === 'get') {
      config.params = {
        random: Math.random(),
        ...config.params
      }
    }
    return config
  },
  error => {
    console.error(error)
    Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    if (response.data.retCode === 2) {
      Error(5000, response.data.msg)
      return Promise.reject(response)
    } else if (response.data.retCode === 1) {
      store.dispatch('LogOut').then(() => {
        window.location.href = '/#/login'
      })
      return Promise.reject(response)
    } else if ((response.data === null || typeof response.data.retCode === 'undefined') && response.config.url.indexOf('aliyun') === -1) {
      Error(5000, '未知错误')
      return Promise.reject(response)
    }
    return response
  },
  error => {
    console.error('err' + error)
    Error(5000, error.message)
    return Promise.reject(error)
  }
)

export default service
